<?php
declare(strict_types=1);

namespace App\Common\Command;

use Core\Basics\BasicsCommand;
use Hyperf\Command\Annotation\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Zms\Unit\Str;
use function Hyperf\Support\env;

#[Command]
class StopCommand extends BasicsCommand
{

    /**
     * 执行的命令行
     *
     * @var null|string
     */
    protected ?string $name = 'app:stop';


    public function __construct(string $name = null)
    {
        parent::__construct($name);
        $this->setDescription('停止醒目运行');
    }



    public function execute(InputInterface $input, OutputInterface $output): int
    {
        $pid_file = BASE_PATH . '/runtime/hyperf.pid';
        $command = '';
        if (file_exists($pid_file)) {
            $pid = (int)(file_get_contents($pid_file) ?: 0);
            exec("ps -ef", $options);
            foreach ($options as $option) {
                $command_info = Str::explode(' ', $option);
                if (intval($command_info[1]) === $pid) {
                    $command = "kill -9 {$pid}";
                    break;
                }
            }
        } else {
            $app = env('APP_NAME');
            $grep = "ps -ef | grep {$app}.Master";
            exec($grep, $options);
            foreach ($options as $option) {
                $command_info = Str::explode(' ', $option);
                if (array_pop($command_info) === "{$app}.Master") {
                    $command = "kill -9 {$command_info[1]}";
                    break;
                }
            }
        }
        if ($command) {
            exec($command);
            $this->output->success('应用已停止');
        } else {
            $this->output->warning('应用当前未运行');
        }
        return parent::execute($input, $output);
    }
}